// 封装分类数据业务相关代码
import { getCategoryAPI } from '@/api/category.js'
import { ref, onMounted, onUnmounted } from 'vue'
import { onBeforeRouteUpdate, useRoute } from "vue-router";

export const useCatefory = () => {
  // 获取分类数据
  const CategoryData = ref({})
  const route = useRoute()
  let getCategoryIntervalID;
  const getCategory = async (id = route.params.id) => {
    if (id === undefined) {
      id = route.params.id
    }
    const res = await getCategoryAPI(id)
    //console.log(res)
    CategoryData.value = res.result
  }
  onMounted(() => {
    getCategory()
    getCategoryIntervalID = setInterval(getCategory, 60000)
  })
  onUnmounted(() => clearInterval(getCategoryIntervalID))

  onBeforeRouteUpdate((to, from) => {
    console.log('路由发生变化')
    if (to.params.id !== from.params.id) {
      getCategory(to.params.id)
    }
  })

  return {
    CategoryData
  }
}